import forge from 'node-forge'
import http from '@/utils/http'

/**
 * 使用非对称加密来加密密码
 * @param {*} data 
 * @returns 
 */
export function useCrypto (data: string): Promise<{ data: string; label: string }> {
  return new Promise((resolve) => {
    http('/pke', {}).then((res: any) => {
      const { label, public_key } = res.data
      const publicKey = forge.pki.publicKeyFromPem(public_key)
      const messageBytes = forge.util.createBuffer(data, 'utf8').getBytes()
      const encrypted = publicKey.encrypt(messageBytes, 'RSA-OAEP', {
        md: forge.md.sha256.create()
      })
      const encrypted64 = forge.util.encode64(encrypted)
      resolve({
        data: encrypted64,
        label
      })
    })
  })
}